package com.cskaoyan.javase.io._8serialization;

import java.io.*;

/**
 * 关于序列化存储多个对象的问题
 * 如果有这种需求,建议不要直接就将多个对象存入文件,尤其是不能追加存入,追加存入在read时可能会产生异常
 * 解决方案:
 * 如果要存多个对象,不要直接存对象,而是存容器(数组,集合)
 *
 * @since 09:34
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 序列化存储Dog对象进a.txt
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("a.txt"));
        Dog d = new Dog("舔狗", 16);
        Dog d2 = new Dog("柯基", 3);
        Dog[] dogs = {d, d2};
        // out.writeObject(d);
        // out.writeObject(d2);
        out.writeObject(dogs);

        out.flush();
        out.close();

        ObjectInputStream in = new ObjectInputStream(new FileInputStream("a.txt"));
        Object result = in.readObject();
        // Object类型强转成对象数组类型是可以的
        Dog[] dogsResult = (Dog[]) result;
        for (Dog dog : dogsResult) {
            System.out.println(dog);
        }

        // Dog result1 = (Dog) in.readObject();
        // Dog result2 = (Dog) in.readObject();
        // System.out.println(result1);
        // System.out.println(result2);

        // Object数组强转成对应类型是不行的
        Object[] arr = {"abc", "666", d, d2};
        String[] strs = (String[]) arr;
    }
}

class Dog implements Serializable {
    private static final long serialVersionUID = 8063531506311567709L;
    private String name;
    private int age;

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Dog{");
        sb.append("name='").append(name).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}